package com.ganbing518.commons.validator;

import com.ganbing518.commons.annotation.EnumValid;
import com.ganbing518.commons.interfaces.EnumInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Description:
 *
 * @author gan bing
 * @version V1.0
 * @date 2018-06-25 16:36
 */
public class EnumValidator implements ConstraintValidator<EnumValid, Object> {

    private final static Logger LOGGER = LoggerFactory.getLogger(EnumValidator.class);

    private Class<?> isEnum;

    @Override
    public void initialize(EnumValid annotation) {
        isEnum = annotation.value();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (this.isEnum == null) {
            return true;
        }
        if (value == null) {
            return false;
        }
        if (isEnum.isEnum()) {
            try {
                Class<Enum> clazz = (Class<Enum>) Class.forName(isEnum.getName());

                Enum[] enums = clazz.getEnumConstants();
                for (Enum obj : enums) {
                    EnumInterface enumInterface = (EnumInterface) obj;
                    if (enumInterface.isExist(value)) {
                        return true;
                    }
                }
            } catch (Exception e) {
                LOGGER.error("加载枚举类异常：" , e);
            }
        }
        return false;
    }
}
